# -*- coding: utf-8 -*-

require "rubygems"
require "json"
#require 'will_paginate'

class TestController < ApplicationController
  before_filter :sys_before_log
  
  #得到控制器中的所有方法
  def getAllMethods
    action_methods.each do |method|
      logger.info method
    end
  end
  

  #得到所有的控制器
  def getAllControllers
    ActionController::Routing::possible_controllers.each do |controller|
      logger.info controller
      logger.info controller.action_methods.size
      #logger.info controller.to_s == "rails_info"
    end
  end

  #保存并插入所有的Controller与Action,如果已经有了，就不插入了。
  #  def saveCA
  #    begin
  #      ActionController::Routing::possible_controllers.each do |controller|
  #        if controller != "rails/info" && controller != "rails_info" && controller != "application" && controller != "test"
  #          ctrl = SysController.find(:first,:conditions=>["name = ?",controller.to_s])
  #          if ctrl == nil
  #            ctrl = SysController.new
  #            ctrl.name = controller.to_s
  #          end
  #
  #          Module.class_eval(controller.humanize.titleize.gsub(" ","")+"Controller").action_methods.each do |action_method|
  #            action = SysAction.find(:first,:conditions=>["name = ? AND sys_controller_id = ?",action_method.to_s,ctrl.id])
  #            if action == nil
  #              action = SysAction.new
  #              action.name = action_method.to_s
  #              ctrl.sys_actions << action
  #            end
  #          end
  #          ctrl.save!
  #        end
  #      end
  #    rescue Exception => e
  #      logger.info "logging......................................................................................."
  #      DbLog.info(1, 1, 1, params[:controller], params[:action], request.remote_ip ,e.to_s)
  #      logger.info e
  #    end
  #  end


  #For Rails 3.0
  def saveCA
    begin
      sysControllers = {}
      con_classes = ObjectSpace.each_object(Class).select {|cls| cls.ancestors[1..-1].include?(ApplicationController) }
      con_classes.each do |cls|
        controller = cls.to_s.underscore
        puts "controller--------------------------------"
        controller =  controller.gsub("_controller","")
        puts controller
        if controller != "test"
          ctrl = SysController.find(:first,:conditions=>["name = ?",controller])
          if ctrl == nil
            ctrl = SysController.new
            ctrl.name = controller.to_s
          end
          puts ctrl.name
          methodsArray = cls.public_instance_methods(false)
          methodsArray = methodsArray.find_all{|n| n.index("_") != 0}
          for sysMethod in methodsArray
            action = SysAction.find(:first,:conditions=>["name = ? AND sys_controller_id = ?",sysMethod.to_s,ctrl.id])
            if action == nil
              action = SysAction.new
              action.name = sysMethod.to_s
              ctrl.sys_actions << action
            end
          end
          ctrl.save!
        end
      end
    rescue Exception => e
      logger.info "logging......................................................................................."
      DbLog.info(1, 1, 1, params[:controller], params[:action], request.remote_ip ,e.to_s)
      logger.info e
    end
  end

  def otherCA1

    ApplicationController.subclasses.each do |c|
      logger.info "Controller: #{c}"
      logger.info "Actions: #{c.constantize.action_methods.collect{|a| a.to_s}.join(', ')}"
    end

  end

  def otherCA
    #    controllers = Dir.new("#{RAILS_ROOT}/app/controllers").entries
    #    controllers.each do |controller|
    #      if controller =~ /_controller/
    #        cont = controller.camelize.gsub(".rb","")
    #        logger.info cont
    #        (eval("#{cont}.new.methods") -
    #            ApplicationController.methods -
    #            Object.methods -
    #            ApplicationController.new.methods).sort.each {|met|
    #          logger.info "\t#{met}"
    #        }
    #      end
    #    end
    logger.info ActionController::Routing::possible_controllers.inspect
    Module.class_eval("AdminController").action_methods.each do |action_method|
      logger.info action_method
    end
  end

  #测试事务与异常捕获
  def testt
    begin
      Sequence.transaction do
        sequence = Sequence.find(:first,:conditions=>["company_id = ? AND sub_type = ?",session[:company_id],SaleOrder.name])
        sequence.seq_no = sequence.seq_no + 1
        sequence.save!
      end
    rescue ActiveRecord::StaleObjectError
      logger.info "somebody using sn before yours.============"
      retry
    rescue ActiveRecord::RecordNotFound
      logger.info "RecordNotFound"
    rescue Exception => e
      logger.info "logging............."
      logger.info e
    end
  end
  
  def test3
    if 1==1
      abc = true
    end
    logger.info abc
  end

  def testclass
    logger.info DeliveryOrder.name
  end

  def substr
    a = "abcdefg"
    logger.info a[0,2]

  end
  
  def test1
    
    #components =  product.components
    #component_goods = product.component_goods
    product = Product.find(3)
    logger.info product.products_components.length
    components = product.components
    
    middle = ProductsComponent.find(1)
    #logger.info middle.product.name
    #logger.info middle.component.name
    for component in components
      #logger.info component.product.name
      logger.info component.name
    end
  end

  

  def getTreeDataJson(categories, parent)
    data = Array.new
    categories.each { |category|
      #if !category.leaf?
      current_text="("+category.id.to_s + ")"+ category.cn_name+"|"+category.tw_name+"|"+category.en_name
      if data.empty?
        #data = [{"text"=>current_text,"cn_text"=>category.cn_name,"tw_text" => category.tw_name,"en_text" =>category.en_name,"id"  => category.id,"cls" => "folder" ,"leaf"  => false,"children" => get_tree(category.children,category) }]
        data = [{"text" => current_text,"id"  => category.id,"cls" => "folder" ,"leaf"  => false,"children" => get_tree(category.children,category) }]
      else
        #if category.children==nil
        #   data.concat([{"text"  =>  category.name,"id"  => category.id,"cls" => "folder" ,"leaf"  => false,"children" => get_tree(category.children,category)}])
        #else
        #  data.concat([{"text"  =>  category.name,"id"  => category.id,"cls" => "folder" ,"leaf"  => true,"children" => get_tree(category.children,category)}])
        #end
        #data.concat([{"text"=>current_text,"cn_text"=>category.cn_name,"tw_text" => category.tw_name,"en_text" =>category.en_name,"id"  => category.id,"cls" => "folder" ,"leaf"  => false,"children" => get_tree(category.children,category)}])
        data.concat([{"text" => current_text,"id" => category.id,"cls" => "folder" ,"leaf" => false,"children" => get_tree(category.children,category)}])
      end
      #else
      # data.concat([{"text" => category.name,"id" => category.id,"cls" => "file","leaf" => true}])
      #end

    }
    return data
  end
  
  def testviewport
    
  end

  def json
    jsonStr =  "{\"goods\":[{\"number\":\"1001\", \"quantity\":\"1\", \"unit_price\":\"1\"},{\"number\":\"1002\", \"quantity\":\"2\", \"unit_price\":\"2\"}]}"
    strHash = JSON.parse jsonStr
    logger.info strHash["products"]
    array1 = strHash["products"]
    logger.info array1.length
    logger.info array1[0]
    logger.info array1[1]
    productHash = array1[0]
    logger.info "--------------------------"
    logger.info productHash["number"]
  end

  def double
    logger.info 2.0-1.1
  end

  def testLog
    DbLog.info(1001, 1, 1, params[:controller], params[:action], request.remote_ip ,"测试")
  end

  def testToJson
    #总菜单
    #totalMenuArray <-- moduleMenuHash <-- subMenuArray <-- subMenuHash
    totalMenuArray = Array.new
    moduleMenuHash = Hash.new
    moduleMenuHash[:id] = 1
    moduleMenuHash[:text] = '采购管理'

    subMenuArray = Array.new
    subMenuHash = Hash.new
    subMenuHash[:id] = 11
    subMenuHash[:url] = 'http://www.163.com'

    subMenuArray << subMenuHash

    moduleMenuHash[:children] = subMenuArray

    totalMenuArray << moduleMenuHash
    @menus = totalMenuArray.to_json
    logger.info @menus
  end

  #数组交集
  def intersection
    a = [1,2,3,4,5]
    logger.info a.include?(6)
    b = [3,4,5,6,7]
    c = a&b
    logger.info c
    logger.info a-c
    logger.info b-c

  end

  def TestNS
    products = ProductsComponent.getAllComponentsByProductId 85
    logger.info products.size
  end

  def getRandomFirst
    puts Customer.find(:first)
    #puts Customer.find(:first,:conditions=>['id=1'])
  end

  def testPaginate
    #customers = Customer.paginate :page => params[:page]||1, :per_page => 2,:order=>'updated_at DESC'
    customers = Customer.paginate :page => 3, :per_page => 5,:order=>'updated_at DESC'
    puts customers
  end

  def testJoin
    saleOrderDetails = SaleOrderDetail.find(:all,:select=>"p.id as product_id,p.name as product_name,p.spec,sd.sale_order_id,sd.quantity,dd.delivery_order_id,dd.quantity ",:joins =>"as sd left join delivery_order_details as dd on sd.product_id = dd.product_id left join products as p on p.id = sd.product_id left join sale_orders as s on sd.sale_order_id = s.id left join delivery_orders as d on dd.delivery_order_id = d.id and d.sale_order_id = s.id where s.id = 17")
    puts saleOrderDetails
    puts saleOrderDetails.to_json()

    respond_to do |format|
      format.html
      format.xml { render :xml => @events.to_xml }
      format.json { render :json => @events.to_json }
      format.atom { @feed_title = "My event list" } # index.atom.builder
    end
  end

  def controllers
    if @controllers.nil?
      @controllers = {}
      con_classes = ObjectSpace.each_object(Class).select {|cls| cls.ancestors[1..-1].include?(ApplicationController) }
      
      con_classes.each do |cls|
        puts cls
        methodsArray = cls.public_instance_methods(false)
        puts methodsArray.join(',')
        methodsArray = methodsArray.find_all{|n| n.index("_") != 0}
        puts methodsArray.join(',')
        @controllers[cls.name.to_sym] = cls.public_instance_methods(false)
      end
    end

    puts con_classes
  end

  def testScan
    puts "GetYouName".underscore
    myC =  "MyNameController".tableize
    myC =  myC.gsub("_controllers","")
    puts myC
    puts "CCCCCCCCCCCCCCCCCCCCCCCCCCCC"
    puts "GetMyName".tableize
    puts "abab".scan(/a/)

    puts "__b_a_c".index("a", 0)

    puts "Get my Name".titleize
    myStr = "Get my Name"
    myNewStr = []
    puts myNewStr.size
    myStr.each_char do |c|
      puts "AAAAAAAAAAAAAAA"
      puts ?e
      puts c[0]
      puts "BBBBBBBBBBBBB"
      if ?c < 91
        if myNewStr.size != 0
          myNewStr << "_"
        end
      end
      myNewStr << c
    end
    puts myNewStr.size
    puts myNewStr.join("")
  end

  def comboTree
    
  end

  def testSession
    #OrderUtil.testSession
    puts OrderUtil.generate_order_number("XS", 0001, "个人", session[:department], session[:employee])
  end

  def testNS
    employees = Employee.registered 7.days.ago
    puts employees[0].name
  end

  def testTime
    puts Time.now
    puts Time.zone.now
    puts Time.new.strftime("%Y-%m-%d %H:%M:%S")
    puts Time.new.strftime("%Y-%m-%d")
  end

  def testInclude
    roleDetails = RolesPrivilegeDetail.find(:first,:include=>[:role])
    puts roleDetails

    roles = Role.find(:first,:include=>[:roles_privilege_details])
    puts roles

    puts SaleOrder.find(:first,:include=>[:sale_order_details])
  end

  def testReport
    Spreadsheet.client_encoding = "UTF-8"
    book = Spreadsheet.open "#{Rails.root.to_s}/report_template/mike_report.xls"
    #book = Spreadsheet.open "#{Rails.root.to_s}/report_template/report.xlsx"
    sheet1 = book.worksheet 0
    row = sheet1.row(11)
    row[2] = '打哈哈'
    book.write "#{RAILS_ROOT}/public/reports/report.xls"

    reportPath = "<a href='/reports/zhengyi_1.xls' target='_blank'>报表下载</a>"
    jsonstr="{success:true,info:'success',path:\"#{reportPath}\"}"
    render :text=>jsonstr, :layout=>false
  end

  def import_product_for_kl
    Spreadsheet.client_encoding = "UTF-8"
    book = Spreadsheet.open "#{Rails.root.to_s}/report_template/first_warehouse.xls"
    #book = Spreadsheet.open "#{Rails.root.to_s}/report_template/report.xlsx"
    sheet0 = book.worksheet 0

    i=2
    while i< 1057 do
      row = sheet0.row(i)
      puts row[1]
      product = Product.new
      product.company_id = 1
      product.vendor_id = 1
      product.number = row[1]
      product.name = row[2].to_s + ":" + row[3].to_s
      product.brand_id = 1
      product.is_suit = 0
      product.unit_price = 1.0
      product.save!
      row[6] = product.id
      i = i+1
    end

    book.write "#{RAILS_ROOT}/public/reports/new_products.xls"

    reportPath = "<a href='/reports/zhengyi_1.xls' target='_blank'>报表下载</a>"
    jsonstr="{success:true,info:'success',path:\"#{reportPath}\"}"
    render :text=>jsonstr, :layout=>false
  end

  def report_from_io
    require 'spreadsheet'
    Spreadsheet.client_encoding = "UTF-8"
    book = Spreadsheet.open "#{Rails.root.to_s}/report_template/sale_order_well.xls"
    #book = Spreadsheet.open "#{Rails.root.to_s}/report_template/report.xlsx"
    sheet1 = book.worksheet 0
    row = sheet1.row(9)
    #row[2] = '打哈哈'
    puts params[:id]
    saleOrder = SaleOrder.find(params[:id],:include=>[:sale_order_details=>:product])
    saleOrderDetails = saleOrder.sale_order_details
    saleOrderDetails.size.times do |i|
      if i == 0
        #row[0] =  saleOrderDetails[i].product.number
        #row[1] =  saleOrderDetails[i].product.name
        #        10.times do |i|
        #          sheet1.insert_row 1,["Fuck You"]
        #        end
        #
        #        10.times do |i|
        #          row.insert 1,"Fuck You"
        #        end
        #row[1] = "Fuck you"
        #        row.push 'Creator of Ruby'
        #        row.unshift 'Yukihiro Matsumoto'
        #        sheet1.row(2).replace [ 'Daniel J. Berger', 'U.S.A.',
        #          'Author of original code for Spreadsheet::Excel' ]
        #        sheet1.row(3).insert 1, 'Unknown..................'
        #        sheet1.update_row 4, 'Hannes Wyss', 'Switzerland', 'Author'
        
        #        new_row = Spreadsheet::Row.new(sheet1,8, ["Fuck!","You!"])
        #        new_row[0] = "Fuck..................."
        #        new_row = Spreadsheet::Row.new(sheet1,9, ["Fuck!","You!"])
        #        new_row[0] = "Fuck..................."
        #        new_row = Spreadsheet::Row.new(sheet1,10, ["Fuck!","You!"])
        #        new_row[0] = "Fuck..................."
        #sheet1.insert_row 8 ,["fuck","at","","you"]
        row.height = 38
        format = Spreadsheet::Format.new :color => :blue, :weight => :bold, :size => 18
        row.default_format = format
        sheet1.row(0).height = 18

        format = Spreadsheet::Format.new :color => :red,
          :weight => :bold,
          :size => 88
        sheet1.row(0).default_format = format

        bold = Spreadsheet::Format.new :weight => :bold
        4.times do |x| sheet1.row(x + 1).set_format(0, bold) end

      else
        row = sheet1::ROW.new
        row.insert 0, saleOrderDetails[i].product.number
        row.insert 1, saleOrderDetails[i].product.name
      end
    end
    book.write "#{Rails.root.to_s}/public/reports/report_X.xls"
    report_io = StringIO.new
    book.write report_io
    send_data report_io.string,:filename => '销售凭证.xls'
  end

  def testRJB
    require 'rubygems'
    require 'rjb'
    puts "Fuck"
    str = Rjb::import("java.lang.String")
    puts str
    puts "End"
  end

  def test_excel
    #require 'rubygems'
    require 'rjb'
    begin
      puts "Begin......................"
      fis = Rjb::import('java.io.FileInputStream')
      fs = Rjb::import("org.apache.poi.poifs.filesystem.POIFSFileSystem")
      hssf = Rjb::import("org.apache.poi.hssf.usermodel.HSSFWorkbook")
      workbook = hssf.new(fs.new(fis.new("#{RAILS_ROOT}/report_template/sale_order_well.xls")))
      puts "workbook................................."
      puts workbook
      puts "End........................"
      #created_at status="" Constants::ORDER_STATUS_YCP
      #logger.error orders.length
      sheet0 = workbook.getSheetAt(0)
      row = sheet0.getRow(0)
      puts "Row................"
      #puts workbook.getTotalSize()
      puts row
      cell = row.getCell(0)
      puts "cell..............."
      puts cell
      puts cell.getStringCellValue()
      cell.setCellValue("!!!!!!!!!!!!!!!!!!")

      fos = Rjb::import('java.io.FileOutputStream')
      fos.new("#{Rails.public_path}/reports/test_1.xls")
      puts "fos................"
      puts fos
      puts "workbook....again"
      puts workbook
      puts workbook.isHidden()

      puts size
      workbook.write(fos)
    rescue Exception => e
      logger.info "Fuck........................................"
      logger.info e
    end
  end

  def new_excel
    require 'spreadsheet'
    require 'parseexcel'
    require 'parseexcel/parseexcel'
    require 'parseexcel/parser'
    Spreadsheet.client_encoding = "UTF-8"
    book = Spreadsheet::Workbook.new
    sheet1 = book.create_worksheet
    #bold = Spreadsheet::Format.new :weight => :bold,:size => 8,:color => :red
    bold = Spreadsheet::Format.new :weight => :bold,:border => 7,:size => 18,:color => :red
    #book = Spreadsheet.open "#{Rails.root.to_s}/report_template/sale_order_well.xls"
    #sheet1 = book.worksheet 0

    sheet1 = book.create_worksheet
    sheet1.name = 'My First Worksheet!'
    sheet1[1,0] = 'Japan'
    row = sheet1.row(1)
    row.push 'Creator of Ruby'
    row.unshift 'Yukihiro Matsumoto'
    sheet1.row(2).replace [ 'Daniel J. Berger', 'U.S.A.',
      'Author of original code for Spreadsheet::Excel' ]
    sheet1.row(3).push 'Charles Lowe', 'Author of the ruby-ole Library'
    sheet1.row(3).insert 1, 'Unknown'
    sheet1.update_row 4, 'Hannes Wyss', 'Switzerland', 'Author'

    #sheet1.row(0).height = 18
    format = Spreadsheet::Format.new :color => :red,
      :weight => :bold,
      :border => 10,
      :size => 38
    #测试插入row
    sheet1.row(0).set_format(0,bold)
    sheet1.row(1).set_format(0,bold)
    puts "Fuck..............."
    row = sheet1.insert_row(1, ["Fuck.","Fuck.","Fuck.","Fuck.","Fuck."])
    row = sheet1.insert_row(1, ["Fuck."])
    row = sheet1.insert_row(1, ["Fuck."])
    row = sheet1.insert_row(1, ["Fuck."])
    row = sheet1.insert_row(1, ["Fuck."])
    puts "Fuck ............end"
    #sheet1.row(0).default_format = format
    
    5.times do |x| sheet1.row(x + 1).set_format(0, bold) end

    book.write "#{Rails.root.to_s}/public/reports/report_Y.xls"
    report_io = StringIO.new
    book.write report_io
    send_data report_io.string,:filename => '销售凭证.xls'
  end

  def sale_order_print
    require 'spreadsheet'    
    #Spreadsheet.client_encoding = "UTF-8"
    #book = Spreadsheet.open "#{Rails.root.to_s}/report_template/sale_order_well.xls"
    book = Spreadsheet.open "#{Rails.root.to_s}/report_template/mike_report.xls"
    sheet1 = book.worksheet 0
    sheet1.name = '销售订单凭据'
    #取得销售订单的详细信息
    saleOrder = SaleOrder.find(params[:id],:include=>[:sell_department,:sales,:customer,:employee,{:sale_order_details=>:product}])
    #填充单据日期
    row = sheet1.row(2)
    row[1]=saleOrder.created_at.strftime("%Y-%m-%d")
    row[4]=saleOrder.order_number
    row = sheet1.row(3)
    row[1] = saleOrder.sell_department.name
    row[4]=saleOrder.sales.name
    row = sheet1.row(4)
    row[1]=saleOrder.customer.name
    saleOrderDetails = saleOrder.sale_order_details
    timeInt = saleOrderDetails.size
    logger.info timeInt
    #定义表格外框格式
    #borderFormat = Spreadsheet::Format.new :weight => :bold,:border => 1,:size => 18,:color => :red
    
    #销售订单中的货品总数
    totalQuantity = 0
    timeInt.times do |x|      
      row = sheet1.row(8+x)
      row[0] =  saleOrderDetails[x].product.number.strip
      row[1] =  saleOrderDetails[x].product.name.strip
      row[3] =  saleOrderDetails[x].quantity
      totalQuantity = totalQuantity + saleOrderDetails[x].quantity
      row[5] =  saleOrderDetails[x].unit_price
      row[6] =  saleOrderDetails[x].amount
    end
    #开始添加汇总一样的信息
    row = sheet1.row(8+timeInt+1)
    row[2] =  "总计:"
    row[3] = totalQuantity
    row[6] =  saleOrder.amount
    
    row = sheet1.row(8+timeInt+2)
    row[0] =  "制单人:"
    row[1] =  saleOrder.employee.name
    row[2] =  "已付金额:"
    row[3] =  saleOrder.rec_amount
    row[4] =  "应收余款:"
    
    row = sheet1.row(8+timeInt+3)
    row[0] =  "仓库签字:"
    row[2] =  "业务员签字:"
    row[4] =  "客户签字:"
    row[6] =  "账务盖章:"
    
    row = sheet1.row(8+timeInt+4)
    row[0] =  "送货地址:"
    row[1] =  saleOrder.delivery_address
    row[4] =  "客户电话:"
    row[5] =  saleOrder.phone
    
    book.write "#{Rails.root.to_s}/public/reports/report_Z.xls"
    report_io = StringIO.new
    book.write report_io
    send_data report_io.string,:filename => '销售凭证.xls'
  end

  def delivery_order_print
    require 'spreadsheet'
    Spreadsheet.client_encoding = "UTF-8"
    book = Spreadsheet.open "#{Rails.root.to_s}/report_template/delivery_order_well.xls"
    sheet1 = book.worksheet 0
    sheet1.name = '销售订单凭据'
    #取得销售订单的详细信息
    deliveryOrder = DeliveryOrder.find(params[:id],:include=>[{:sale_order=>[:sell_department,:sales]},:customer,:employee,:warehouse,{:delivery_order_details=>:product}])
    #填充单据日期
    row = sheet1.row(2)
    row[1]= deliveryOrder.created_at.strftime("%Y-%m-%d")
    row[4]= deliveryOrder.order_number
    row = sheet1.row(3)
    row[1]= deliveryOrder.sale_order.sell_department.name
    row[4]= deliveryOrder.sale_order.sales.name
    row = sheet1.row(4)
    row[1]= deliveryOrder.customer.name
    row[4]= deliveryOrder.warehouse.name
    deliveryOrderDetails = deliveryOrder.delivery_order_details
    timeInt = deliveryOrderDetails.size
    logger.info timeInt
    totalQuantity = 0
    timeInt.times do |x|
      row = sheet1.row(8+x)
      row[0] =  deliveryOrderDetails[x].product.number.strip
      row[1] =  deliveryOrderDetails[x].product.name.strip
      row[3] =  deliveryOrderDetails[x].quantity
      totalQuantity = totalQuantity + deliveryOrderDetails[x].quantity
      #row[6] =  saleOrderDetails[x].unit_price
      #row[7] =  saleOrderDetails[x].amount
    end
    #开始添加汇总一样的信息
    row = sheet1.row(8+timeInt+1)
    row[2] =  "总计:"
    row[3] =  totalQuantity

    row = sheet1.row(8+timeInt+2)
    row[0] =  "制单人:"
    row[1] =  deliveryOrder.employee.name
    row[2] =  "已付金额:"
    #srow[3] =  deliveryOrder.rec_amount
    row[4] =  "应收余款:"

    row = sheet1.row(8+timeInt+3)
    row[0] =  "仓库签字:"
    row[2] =  "业务员签字:"
    row[4] =  "客户签字:"
    row[6] =  "账务盖章:"

    row = sheet1.row(8+timeInt+4)
    row[0] =  "送货地址:"
    row[1] =  deliveryOrder.sale_order.delivery_address
    row[4] =  "客户电话:"
    row[5] =  deliveryOrder.sale_order.phone

    book.write "#{Rails.root.to_s}/public/reports/report_D.xls"
    report_io = StringIO.new
    book.write report_io
    send_data report_io.string,:filename => '销售出库凭证.xls'
  end

  def loan_delivery_print
    require 'spreadsheet'
    Spreadsheet.client_encoding = "UTF-8"
    book = Spreadsheet.open "#{Rails.root.to_s}/report_template/loan_delivery_well.xls"
    sheet1 = book.worksheet 0
    sheet1.name = '借货订单凭据'
    #取得销售订单的详细信息
    loanDelivery = LoanDelivery.find(params[:id],:include=>[{:loan=>[:department,:sales]},:customer,:employee,:warehouse,{:loan_delivery_details=>:product}])
    #填充单据日期
    row = sheet1.row(2)
    row[1]= loanDelivery.created_at.strftime("%Y-%m-%d")
    row[4]= loanDelivery.order_number
    row = sheet1.row(3)
    row[1]= loanDelivery.loan.department.name
    row[4]= loanDelivery.loan.sales.name
    row = sheet1.row(4)
    row[1]= loanDelivery.customer.name
    row[4]= loanDelivery.warehouse.name
    loanDeliveryDetails = loanDelivery.loan_delivery_details
    timeInt = loanDeliveryDetails.size
    logger.info timeInt
    totalQuantity = 0
    timeInt.times do |x|
      row = sheet1.row(8+x)
      row[0] =  loanDeliveryDetails[x].product.number.strip
      row[1] =  loanDeliveryDetails[x].product.name.strip
      row[3] =  loanDeliveryDetails[x].quantity
      totalQuantity = totalQuantity + loanDeliveryDetails[x].quantity
      #row[6] =  saleOrderDetails[x].unit_price
      #row[7] =  saleOrderDetails[x].amount
    end
    #开始添加汇总一样的信息
    row = sheet1.row(8+timeInt+1)
    row[2] =  "总计:"
    row[3] =  totalQuantity

    row = sheet1.row(8+timeInt+2)
    row[0] =  "制单人:"
    row[1] =  loanDelivery.employee.name
    row[2] =  "已付金额:"
    #srow[3] =  deliveryOrder.rec_amount
    row[4] =  "应收余款:"

    row = sheet1.row(8+timeInt+3)
    row[0] =  "仓库签字:"
    row[2] =  "业务员签字:"
    row[4] =  "客户签字:"
    row[6] =  "账务盖章:"

    row = sheet1.row(8+timeInt+4)
    row[0] =  "送货地址:"
    row[1] =  loanDelivery.loan.delivery_address
    row[4] =  "客户电话:"
    row[5] =  loanDelivery.loan.phone

    book.write "#{Rails.root.to_s}/public/reports/report_JD.xls"
    report_io = StringIO.new
    book.write report_io
    send_data report_io.string,:filename => '借货出库凭证.xls'
  end
  
  def purchase_order_print
    require 'spreadsheet'
    Spreadsheet.client_encoding = "UTF-8"
    book = Spreadsheet.open "#{Rails.root.to_s}/report_template/purchase_order_well.xls"
    sheet1 = book.worksheet 0
    sheet1.name = '销售订单凭据'
    #取得销售订单的详细信息
    purchaseOrder = PurchaseOrder.find(params[:id],:include=>[:department,:vendor,:employee,{:purchase_order_details=>:product}])
    #填充单据日期
    row = sheet1.row(2)
    row[1] = purchaseOrder.created_at.strftime("%Y-%m-%d")
    row[4] = purchaseOrder.order_number
    row = sheet1.row(3)
    row[1] = purchaseOrder.department.name
    row[4] = purchaseOrder.employee.name
    row = sheet1.row(4)
    row[1] = purchaseOrder.vendor.name
    purchaseOrderDetails = purchaseOrder.purchase_order_details
    timeInt = purchaseOrderDetails.size
    logger.info timeInt
    #采购总数
    totalQuantity = 0
    timeInt.times do |x|
      row = sheet1.row(8+x)
      row[0] =  purchaseOrderDetails[x].product.number.strip
      row[1] =  purchaseOrderDetails[x].product.name.strip
      row[3] =  purchaseOrderDetails[x].quantity
      row[5] =  purchaseOrderDetails[x].unit_price.to_f
      row[6] =  purchaseOrderDetails[x].amount.to_f
      totalQuantity = totalQuantity + purchaseOrderDetails[x].quantity
    end
    #开始添加汇总一样的信息
    row = sheet1.row(8+timeInt+1)
    row[2] =  "总计:"
    row[3] =  totalQuantity
    row[6] =  purchaseOrder.amount

    row = sheet1.row(8+timeInt+2)
    row[0] =  "制单人:"
    row[1] =  purchaseOrder.employee.name
    row[2] =  "已付金额:"
    #row[3] =  purchaseOrder.rec_amount
    row[4] =  "应收余款:"

    row = sheet1.row(8+timeInt+3)
    row[0] =  "仓库签字:"
    row[2] =  "采购员签字:"
    row[4] =  "客户签字:"
    row[6] =  "账务盖章:"

    row = sheet1.row(8+timeInt+4)
    row[0] =  "送货地址:"
    row[1] =  purchaseOrder.delivery_address
    row[4] =  "客户电话:"
    row[5] =  purchaseOrder.phone

    book.write "#{Rails.root.to_s}/public/reports/report_c.xls"
    report_io = StringIO.new
    book.write report_io
    send_data report_io.string,:filename => '采购凭证.xls'
  end
  
  def testInclude
    puts "中国万岁".include? "你好"
  end

  def request_ip
    puts request.remote_ip
  end

  def test_include
    sale = SaleOrder.find(87,:include=>[:sales,{:purchase_order_details=>:purchase_order}])
    puts sale
    #puts sale.to_json(:include=>  {:sales, {:purchase_order_details =>{:include => :purchase_order}}})
    #puts sale.to_json(:include=>  {:sales, {:purchase_order_details =>{:include => :purchase_order}}})
    #puts sale.to_json(:include=>  { :purchase_order_details =>{:include => :purchase_order}})
    #puts sale.to_json(:include=>  {:purchase_order_details =>{:include => :purchase_order}})

    puts sale.to_json(:include=>{:sales => {}, :purchase_order_details=>{:include=>:purchase_order}})
    #puts sale.to_json(:include=>[{:address => {}}, {:job=>{:include=>:paygrade}}])
    #@asset.to_json(:include => { :asset_statuses => {:include => :asset_status_name}})

  end


  #得到仓库中的产品数量
  def getProductStockQuantity
    productId = params[:id]
    puts ProductCollection.where("product_id = #{productId}").sum(:quantity)
  end

  def printArray
    array = Array.new
    array << 1
    array << 3
    array << 5
    SaleReturned.delete_all(["id in(?)",array])
  end

  def strToArray
    a = "1,2,3,4,5".to_a
    puts a
  end

  def testObjNil
    if 1==2
      test = 1
    end
    puts test.nil?
    puts !test.nil?
  end

  def ArrayToStr
    testArray = Array.new
    testArray << 1
    testArray << 3
    testArray << 5
    puts testArray.join(",")
  end

  def testArrayJoin
    testA = Array.new
    testA << 132
    testA << 139
    puts testA
    puts testA.join(",")
  end

  def dateTest
    puts "30".to_i.days
    puts Time.now + "60".to_i.days
  end

  #导入期初数，2010盘点上线前测试,这个方法用来测试，编号一样，产品名不一样的情况。
  def import_product_for_os
    Spreadsheet.client_encoding = "UTF-8"
    book = Spreadsheet.open "#{Rails.root.to_s}/report_template/2011_os.xls"
    #book = Spreadsheet.open "#{Rails.root.to_s}/report_template/report.xlsx"
    sheet0 = book.worksheet 0

    i=1
    logger.info "Fuc..............K"
    logger.info sheet0

    productHash = Hash.new
    repeatJ = 0
    repeatPNK = 0 
    while i< 1621 do
      #logger.info "当前是第："+(i-1).to_s+"行"
      row = sheet0.row(i)      
      #如果没有此产品则录入。
      if productHash["#{row[1]}"].nil?
        if row[3] !=nil
          productHash["#{row[1]}"] = row[3].strip
          #logger.info row[3].strip
        end
      else
        #如果已经有了此编号了，刚检查一下，里面产品名与当前的是不是一样的。
        if productHash["#{row[1]}"] == row[3].strip
          #logger.info "产品重复"
          repeatPNK = repeatPNK + 1
        else
          logger.info "产品无重复，编号重复........................................................................................"
          logger.info productHash["#{row[1]}"]
          logger.info row[3].strip
          repeatJ = repeatJ + 1
          logger.info "行数:" + (i+1).to_s
        end
      end
      i = i+1
    end
    logger.info "productHash:"+productHash.size.to_s
    logger.info "编辑重复了:"+repeatJ.to_s
    jsonstr="{success:true,info:'success'}"
    render :text=>jsonstr, :layout=>false
  end

  #导入期初数，2010盘点上线前测试,这个方法用来测试，产品名一样，但编号不一样的情况。
  def import_product_for_os_1
    Spreadsheet.client_encoding = "UTF-8"
    book = Spreadsheet.open "#{Rails.root.to_s}/report_template/2011_os.xls"
    #book = Spreadsheet.open "#{Rails.root.to_s}/report_template/report.xlsx"
    sheet0 = book.worksheet 0

    i=1
    productHash = Hash.new
    repeatJ = 0
    repeatPNK = 0
    while i< 1582 do
      #logger.info "当前是第："+(i-1).to_s+"行"
      row = sheet0.row(i)
      #如果没有此产品则录入。
      if productHash["#{row[3]}"].nil?
        if row[1] !=nil
          productHash["#{row[3]}"] = row[1].strip
          #logger.info row[3].strip
        end
      else
        if row[1].nil?
          logger.info "这一行row[1]是空的：" + (i+1).to_s
        end
        #如果已经有了此编号了，刚检查一下，里面产品名与当前的是不是一样的。
        if productHash["#{row[3]}"] == row[1].strip
          #logger.info "产品重复"
          repeatPNK = repeatPNK + 1
        else
          logger.info "编号无重复，产品重复........................................................................................"
          logger.info productHash["#{row[3]}"]
          logger.info row[1].strip
          repeatJ = repeatJ + 1
          logger.info "行数:" + (i+1).to_s
        end
      end
      i = i+1
    end
    logger.info "productHash:"+productHash.size.to_s
    logger.info "编辑重复了:"+repeatJ.to_s
    jsonstr="{success:true,info:'success'}"
    render :text=>jsonstr, :layout=>false
  end

  #开始导入2010年的所有盘点后的产品
  def import_2011_all_product
    Spreadsheet.client_encoding = "UTF-8"
    book = Spreadsheet.open "#{Rails.root.to_s}/report_template/2011_os.xls"
    #book = Spreadsheet.open "#{Rails.root.to_s}/report_template/report.xlsx"
    sheet0 = book.worksheet 0

    i=1
    
    while i< 1582 do
      logger.info "当前是第："+(i-1).to_s+"行"
      row = sheet0.row(i)

      product = Product.new
      product.company_id = 1
      product.vendor_id = 1
      product.number = row[1].strip
      product.name = row[2].to_s.strip + ":" + row[3].to_s.strip
      product.brand_id = 1
      product.is_suit = 0
      product.unit_price = row[9]
      product.save!
      
      i = i+1
    end
    logger.info "插入条件是:"+i.to_s
    jsonstr="{success:true,info:'success'}"
    render :text=>jsonstr, :layout=>false
  end

  #开始导入2010年的所有盘点后的产品
  def import_for_all_os
    Spreadsheet.client_encoding = "UTF-8"
    book = Spreadsheet.open "#{Rails.root.to_s}/report_template/2011_all.xls"
    #book = Spreadsheet.open "#{Rails.root.to_s}/report_template/report.xlsx"
    sheet0 = book.worksheet 0

    #    i=2
    #
    #    while i< 224 do
    #      logger.info "当前是第："+(i-1).to_s+"行"
    #      row = sheet0.row(i)
    #
    #      product = Product.find_by_number(row[1].to_s.strip)
    #      if product != nil
    #        row[10] = product.id
    #      end
    #
    #      i = i+1
    #    end

    #大库
    #    sheet1 = book.worksheet 1
    #    i=2
    #    while i< 960 do
    #      logger.info "当前是第："+(i-1).to_s+"行"
    #      row = sheet1.row(i)
    #
    #      product = Product.find_by_number(row[1].to_s.strip)
    #      if product != nil
    #        row[10] = product.id
    #      end
    #
    #      i = i+1
    #    end

    #直进直出
    #    sheet2 = book.worksheet 2
    #    i=2
    #    while i< 378 do
    #      logger.info "当前是第："+(i-1).to_s+"行"
    #      row = sheet2.row(i)
    #
    #      product = Product.find_by_number(row[1].to_s.strip)
    #      if product != nil
    #        row[10] = product.id
    #      end
    #
    #      i = i+1
    #    end

    #报溢库
    sheet3 = book.worksheet 3
    i=2
    while i< 35 do
      logger.info "当前是第："+(i-1).to_s+"行"
      row = sheet3.row(i)

      product = Product.find_by_number(row[1].to_s.strip)
      if product != nil
        row[10] = product.id
      end

      i = i+1
    end
    
    book.write "#{Rails.root.to_s}/report_template/2011_all_ok.xls"
    logger.info "插入条件是:"+i.to_s
    jsonstr="{success:true,info:'success'}"
    render :text=>jsonstr, :layout=>false
  end

  #开始导入2010年的所有盘点后的产品
  def import_for_2011_os
    Spreadsheet.client_encoding = "UTF-8"
    book = Spreadsheet.open "#{Rails.root.to_s}/report_template/2011_all_no_f_3.xls"
    #book = Spreadsheet.open "#{Rails.root.to_s}/report_template/report.xlsx"
    

    #1.工程库期初
    #sheet0 = book.worksheet 0
    #    openingStock = OpeningStock.new
    #    openingStock.company_id = 1
    #    openingStock.department_id = 10
    #    openingStock.employee_id = 2
    #    openingStock.vendor_id = 1
    #    openingStock.warehouse_id = 1
    #    openingStock.amount = 1
    #    openingStock.action_date = '2011-01-01'

    i=2

    #    while i< 222 do
    #      logger.info "当前是第："+(i+1).to_s+"行"
    #      row = sheet0.row(i)
    #      logger.info "产品编号:" + row[1].to_s
    #      logger.info "产品Id:" + row[10].to_s
    #      logger.info "产品数量:" + row[8].to_s
    #      logger.info "产品单价:" + row[5].to_s
    #      logger.info "产品总价:" + row[6].to_s
    #
    #      openingStockDetail = OpeningStockDetail.new
    #      openingStockDetail.product_id = row[10].to_s.to_i
    #      openingStockDetail.quantity = row[8].to_s.to_i
    #      openingStockDetail.unit_price = row[5].to_s.to_d
    #      openingStockDetail.amount = row[6].to_s.to_d
    #      openingStock.opening_stock_details << openingStockDetail
    #      i = i+1
    #    end


    #2.大库期初
    #    sheet1 = book.worksheet 1
    #    openingStock = OpeningStock.new
    #    openingStock.company_id = 1
    #    openingStock.department_id = 10
    #    openingStock.employee_id = 2
    #    openingStock.vendor_id = 1
    #    openingStock.warehouse_id = 2
    #    openingStock.amount = 1
    #    openingStock.action_date = '2011-01-01'
    #
    #    i=2
    #
    #    while i< 958 do
    #      logger.info "当前是第："+(i+1).to_s+"行"
    #      row = sheet1.row(i)
    #      logger.info "产品编号:" + row[1].to_s
    #      logger.info "产品Id:" + row[10].to_s
    #      logger.info "产品数量:" + row[8].to_s
    #      logger.info "产品单价:" + row[5].to_s
    #      logger.info "产品总价:" + row[6].to_s
    #
    #      openingStockDetail = OpeningStockDetail.new
    #      openingStockDetail.product_id = row[10].to_s.to_i
    #      openingStockDetail.quantity = row[8].to_s.to_i
    #      openingStockDetail.unit_price = row[5].to_s.to_d
    #      openingStockDetail.amount = row[6].to_s.to_d
    #      openingStock.opening_stock_details << openingStockDetail
    #      i = i+1
    #    end
    

    #3.直进直出
    #    sheet2 = book.worksheet 2
    #    openingStock = OpeningStock.new
    #    openingStock.company_id = 1
    #    openingStock.department_id = 10
    #    openingStock.employee_id = 2
    #    openingStock.vendor_id = 1
    #    openingStock.warehouse_id = 3
    #    openingStock.amount = 1
    #    openingStock.action_date = '2011-01-01'
    #
    #    i=2
    #
    #    while i< 376 do
    #      logger.info "当前是第："+(i+1).to_s+"行"
    #      row = sheet2.row(i)
    #      logger.info "产品编号:" + row[1].to_s
    #      logger.info "产品Id:" + row[10].to_s
    #      logger.info "产品数量:" + row[8].to_s
    #      logger.info "产品单价:" + row[5].to_s
    #      logger.info "产品总价:" + row[6].to_s
    #
    #      openingStockDetail = OpeningStockDetail.new
    #      openingStockDetail.product_id = row[10].to_s.to_i
    #      openingStockDetail.quantity = row[8].to_s.to_i
    #      openingStockDetail.unit_price = row[5].to_s.to_d
    #      openingStockDetail.amount = row[6].to_s.to_d
    #      openingStock.opening_stock_details << openingStockDetail
    #      i = i+1
    #    end

    #4.报溢
    sheet3 = book.worksheet 3
    openingStock = OpeningStock.new
    openingStock.company_id = 1
    openingStock.department_id = 10
    openingStock.employee_id = 2
    openingStock.vendor_id = 1
    openingStock.warehouse_id = 5
    openingStock.amount = 1
    openingStock.action_date = '2011-01-01'

    i=2

    while i< 33 do
      logger.info "当前是第："+(i+1).to_s+"行"
      row = sheet3.row(i)
      logger.info "产品编号:" + row[1].to_s
      logger.info "产品Id:" + row[10].to_s
      logger.info "产品数量:" + row[8].to_s
      logger.info "产品单价:" + row[5].to_s
      logger.info "产品总价:" + row[6].to_s

      openingStockDetail = OpeningStockDetail.new
      openingStockDetail.product_id = row[10].to_s.to_i
      openingStockDetail.quantity = row[8].to_s.to_i
      openingStockDetail.unit_price = row[5].to_s.to_d
      openingStockDetail.amount = row[6].to_s.to_d
      openingStock.opening_stock_details << openingStockDetail
      i = i+1
    end
    
    openingStock.save!

    logger.info "插入条数是:"+i.to_s
    jsonstr="{success:true,info:'success'}"
    render :text=>jsonstr, :layout=>false
  end

  def task_mgr
    
  end

  #清除所有名字和编号完全一样的记录,这个方面是直接删除没有使用的产品
  def clearRepeatProduct
    #select id,count(*),number,name from products group by number,name having count(*) > 1
    products = Product.find(:all,:select=>"id,number,name",:group=>"number,name HAVING COUNT(*) > 1")
    beUsed = false
    i = 0
    products.each do |product|
      productRepeats = Product.find(:all,:conditions=>["name = ? AND number = ?",product.name,product.number])
      productRepeats.each do |productRepeat|
        logger.info "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
        logger.info "productRepeat.sale_order_details.length+++++++++++++++++++++++++++++++++++++++++++++++++"
        if productRepeat.sale_order_details.length > 0
          logger.info productRepeat.sale_order_details.length
          next
        end
        logger.info "productRepeat.purchase_order_details.length+++++++++++++++++++++++++++++++++++++++++++++++++"
        if productRepeat.purchase_order_details.length > 0
          logger.info productRepeat.purchase_order_details.length
          next
        end
        logger.info "productRepeat.opening_stock_details.length+++++++++++++++++++++++++++++++++++++++++++++++++"
        if productRepeat.opening_stock_details.length > 0
          logger.info productRepeat.opening_stock_details.length
          next
        end
        if productRepeat.warehousing_entry_details.length > 0
          next
        end
        logger.info "有一个产品从来没有用到。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。"
        logger.info productRepeat.id
        Product.delete(productRepeat.id)
        i= i + 1
        #如果在以上表中没有数据存在，则删除此产品
      end
    end

    logger.info "fucking............i...................................."
    logger.info i
  end

  #清除所有名字和编号完全一样的记录,这个方法是删除有使用的重重产品，前提是Id大的变为使用Id小的。而且价格一定要相同
  def clearRepeatProduct2
    #select id,count(*),number,name from products group by number,name having count(*) > 1
    products = Product.find(:all,:select=>"id,number,name",:group=>"number,name HAVING COUNT(*) = 2")
    productId = 0
    i = 0
    products.each do |product|
      productRepeats = Product.find(:all,:conditions=>["name = ? AND number = ?",product.name,product.number])
      productRepeats.each do |productRepeat|
        if productId == 0
          productId = productRepeat.id
        elsif productId < productRepeat.id
          logger.info "我烤。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。果然后者大"
          logger.info productId
          logger.info productRepeat.id
          logger.info product.number
          SaleOrderDetail.update_all("product_id = #{productId}","product_id = #{productRepeat.id}")
          PurchaseOrderDetail.update_all("product_id = #{productId}","product_id = #{productRepeat.id}")
          OpeningStockDetail.update_all("product_id = #{productId}","product_id = #{productRepeat.id}")
          i = i + 1
        end
      end
      productId = 0
    end

    logger.info "fucking............i...................................."
    logger.info i
  end

  def difArray
    a = [1,2,3]
    b = a
    a= a - [1]
    logger.info a
    logger.info b

    test = SaleOrderDetail.new
    test.new_amount = 100
    test.unit_price = 100
    logger.info test.to_json
    logger.info '中文'.to_json
  end

  #导入产品，2010盘点上线前测试,这个方法用来测试，编号一样，产品名不一样的情况。
  def import_product_for_gaoyi
    Spreadsheet.client_encoding = "UTF-8"
    book = Spreadsheet.open "#{Rails.root.to_s}/report_template/gaoyi2011.xls"
    #book = Spreadsheet.open "#{Rails.root.to_s}/report_template/report.xlsx"
    sheet0 = book.worksheet 0

    i=1
    logger.info sheet0

    productHash = Hash.new
    repeatJ = 0
    repeatPNK = 0
    while i< 187 do
      #logger.info "当前是第："+(i-1).to_s+"行"
      row = sheet0.row(i)
      #如果没有此产品则录入。
      if productHash["#{row[1]}"].nil?
        if row[3] !=nil
          productHash["#{row[1]}"] = row[2].to_s.strip
          #logger.info row[3].strip
        end
      else
        #如果已经有了此编号了，刚检查一下，里面产品名与当前的是不是一样的。
        if productHash["#{row[1]}"] == row[2].to_s.strip
          #logger.info "产品重复"
          repeatPNK = repeatPNK + 1
        else
          logger.info "产品无重复，编号重复........................................................................................"
          logger.info productHash["#{row[1]}"]
          logger.info row[3].strip
          repeatJ = repeatJ + 1
          logger.info "行数:" + (i+1).to_s
        end
      end
      i = i+1
    end

    #验证第二个Sheet
    sheet0 = book.worksheet 1

    i=1
    logger.info sheet0
    
    repeatJ = 0
    repeatPNK = 0
    while i< 178 do
      #logger.info "当前是第："+(i-1).to_s+"行"
      row = sheet0.row(i)
      #如果没有此产品则录入。
      if productHash["#{row[1]}"].nil?
        if row[3] !=nil
          productHash["#{row[1]}"] = row[2].to_s.strip
          #logger.info row[3].strip
        end
      else
        #如果已经有了此编号了，刚检查一下，里面产品名与当前的是不是一样的。
        if productHash["#{row[1]}"] == row[2].to_s.strip
          #logger.info "产品重复"
          repeatPNK = repeatPNK + 1
        else
          logger.info "产品无重复，编号重复........................................................................................"
          logger.info productHash["#{row[1]}"]
          logger.info row[2].strip
          repeatJ = repeatJ + 1
          logger.info "行数:" + (i+1).to_s
        end
      end
      i = i+1
    end
    
    logger.info "productHash:"+productHash.size.to_s
    logger.info "编辑重复了:"+repeatJ.to_s
    productHash.each do |key|
      logger.info key
      logger.info key[0]
      logger.info key[1]
      logger.info productHash[key]
      product = Product.new
      product.company_id = 1
      product.vendor_id = 15
      product.number = key[0]
      product.name = key[1]
      product.save!
    end
    jsonstr="{success:true,info:'success'}"
    render :text=>jsonstr, :layout=>false
  end

  #导入产品，2010盘点上线前测试,这个方法用来测试，编号一样，产品名不一样的情况。
  def import_os_for_gaoyi
    Spreadsheet.client_encoding = "UTF-8"
    book = Spreadsheet.open "#{Rails.root.to_s}/report_template/gaoyi2011.xls"
    #book = Spreadsheet.open "#{Rails.root.to_s}/report_template/report.xlsx"
    sheet0 = book.worksheet 0

    i=1
    logger.info sheet0

    productHash = Hash.new
    repeatJ = 0
    repeatPNK = 0

    openingStock = OpeningStock.new
    openingStock.company_id = 1
    openingStock.department_id = 10
    openingStock.employee_id = 2
    openingStock.vendor_id = 15
    openingStock.warehouse_id = 1
    openingStock.amount = 0
    openingStock.action_date = '2011-01-01'

    while i< 187 do
      #logger.info "当前是第："+(i-1).to_s+"行"
      row = sheet0.row(i)
      #如果没有此产品则录入。
      product = Product.find_by_number row[1]
      openingStockDetail = OpeningStockDetail.new
      openingStockDetail.product_id = product.id
      openingStockDetail.quantity = row[3].to_s.to_i
      openingStockDetail.unit_price = 0
      openingStockDetail.amount = 0
      openingStock.opening_stock_details << openingStockDetail
      i = i+1
    end
    openingStock.save!

    #验证第二个Sheet
    sheet0 = book.worksheet 1

    i=1
    logger.info sheet0

    openingStock = OpeningStock.new
    openingStock.company_id = 1
    openingStock.department_id = 10
    openingStock.employee_id = 2
    openingStock.vendor_id = 15
    openingStock.warehouse_id = 1
    openingStock.amount = 0
    openingStock.action_date = '2011-01-01'
    
    repeatJ = 0
    repeatPNK = 0
    while i< 178 do
      #logger.info "当前是第："+(i-1).to_s+"行"
      row = sheet0.row(i)
      #如果没有此产品则录入。
      product = Product.find_by_number row[1]
      openingStockDetail = OpeningStockDetail.new
      openingStockDetail.product_id = product.id
      openingStockDetail.quantity = row[3].to_s.to_i
      openingStockDetail.unit_price = 0
      openingStockDetail.amount = 0
      openingStock.opening_stock_details << openingStockDetail      
      i = i+1
    end

    openingStock.save!
    logger.info "productHash:"+productHash.size.to_s
    logger.info "编辑重复了:"+repeatJ.to_s
    jsonstr="{success:true,info:'success'}"
    render :text=>jsonstr, :layout=>false
  end

  #2010-05-04
  def import_product_for_gaoyi
    Spreadsheet.client_encoding = "UTF-8"
    #book = Spreadsheet.open "#{Rails.root.to_s}/report_template/gy_price_201012.xls"
    #book = Spreadsheet.open "#{Rails.root.to_s}/report_template/report.xlsx"
    book = Spreadsheet.open "#{Rails.root.to_s}/report_template/gy_new_product.xls"
    sheet0 = book.worksheet 0

    i=1
    logger.info sheet0

    productHash = Hash.new

    while i< 4136 do
      #logger.info "当前是第："+(i-1).to_s+"行"
      row = sheet0.row(i)
      #如果没有此产品则录入。
      logger.info "row[1]................"
      logger.info row[1].to_s.strip
      product = Product.new
      product.company_id = 1
      product.vendor_id = 1
      product.brand_id = 1
      product.is_suit = 0
      product.number = row[0]
      product.name = row[1]
      product.unit_price = row[2]
      product.save!
      i = i+1
    end

    logger.info i

    jsonstr="{success:true,info:'success'}"
    render :text=>jsonstr, :layout=>false
  end
  
  #测试表的别名
  def testTAS
    pces = ProductCollection.find(:all,:select=>"pc.id",:from=>'product_collections pc')
    logger.info pces.length
  end

  #我们
  def rails3_test
    customers = Customer.name_like "王",'true'
    logger.info customers.to_json(:include=>[:adder,:editor])
  end

  def test_tr
    PurchaseOrderDetail.transaction do
      PurchaseOrderDetail.delete_all("id = 1")
      purchaseOrderDetail = PurchaseOrderDetail.find(:all,:conditions=>["id=10000"])
      logger.info "Not........................................................."
      logger.info purchaseOrderDetail.length
      logger.info purchaseOrderDetail.created_at
    end
  end

  #测试定义局部变量
  def lv
    i = 0
    if i == 0
      info = "成功"
    else
      info = "失败"
    end
    logger.info info

    logger.info 15531.90/14
  end

  #测试云台请求
  def camreq
    
  end

  #测试云台请求
  def camtest

  end

  def strLen
    puts "56".to_s.length
  end

  def testbyDef
    @testVal = 1000001
    logger.info @testVal
    testbyDef2
    logger.info @testVal
    testbyDef3 @testVal
    logger.info @testVal
  end

  def testbyDef2
    @testVal = 1000002
    logger.info @testVal
  end

  def testbyDef3 testVal
    testVal = 1000003
    logger.info testVal
  end

  def strByRef
    myStr = "hello"
    logger.info myStr
    strByRef2! myStr
    logger.info myStr
  end

  def strByRef2! myStr
    myStr = "hello world"
    logger.info myStr    
  end

  def teststrref
    person1 = "Tim"
    person2 = person1
    #person1[0] = 'J'
    person1 = "Jim"
    puts person1
    puts person2

    a = 1000
    b = a
    a = 1001
    puts a
    puts b
  end


  def testgsub
    logger.info "iption\\\":\\\"\\\"".gsub("/\/","")
    logger.info "\\\"description\\\"".gsub(/\\\"/,"\"")
    puts 1555*0.885
    puts "Fuck............."
  end

  def testSQL
    products = Product.where("id not in (select product_id from cost_prices)")
    logger.info "Fuck.............."
    logger.info products.length
    
  end

  def testArray1
    a1 = Array.new
    a2 = Array.new
    a1 << 1
    a1 << 3
    #a1 << 5
    a2 << 2
    a2 << 4
    #a2 << 5
    a3 = a1 & a2
    a4 = a1 + a2
    logger.info "Fucking....................................................."
    logger.info a3.length
    logger.info a3
    logger.info a3 == nil
    logger.info a3 == ""
    logger.info a4
    logger.info "Fucking..................................................End"
  end

  def suit_cost_price
    ActiveRecord::Base.connection.execute("update cost_prices cp set cp.cost_price = null,cp.tax_price = null
where cp.product_id in (select distinct p1.id from products p1,products_components pc1 where p1.id = pc1.product_id)
      AND cp.company_id = 1 AND cp.cal_year = 2011 AND cp.cal_month = 6
      ")
    Product.suit_cost_price(2011,6,1,1,0)
  end

  def get_components
    product = Product.find(274)
    components = product.components
    components.each do |component|
      logger.info component.name
    end
    logger.info "这全是套组。。。。。。。。。。。。。。。。。。。。。。。。。"
    products = product.products
    logger.info "products.length:"+products.length.to_s
    products.each do |subProduct|
      logger.info subProduct.name
    end
  end

  def tool_tip
    logger.info "tool_tip.................................................."
    diffs =  PurchaseOrder.diff_purchase_entry(19)
    logger.info diffs.length
    diffs =  SaleOrder.diff_sale_delivery(25)
    logger.info diffs.length
  end

  def delivery_status
    diffs = SaleOrder.diff_sale_delivery(325)
    logger.info(diffs.length  );
    logger.info(diffs.to_json())
  end

  def multijson
    paramsHash = JSON.parse "{\"name\":123,\"age\":123}"
    logger.info paramsHash
    paramsHash = JSON.parse "{\"customer_id\":55,\"default_discount\":\"0.25\",\"contract_number\":\"\",\"linkman\":\"\\u5f20\\u9759\",\"phone\":\"029-85328622\\uff0c13991201644\",\"action_date\":\"2011-11-14\",\"tax_rate\":\"17\",\"delivery_address\":\"\\u897f\\u5b89\\u5e02\\u96c1\\u5c55\\u8def1\\u53f7\\u66f2\\u6c5f\\u4f1a\\u5c55\\u56fd\\u9645D\\u5ea78\\u5c42\",\"sale_type_id\":1,\"sales_id\":7,\"description\":\"\",\"sales_strategy_id\":1,\"sell_dept_id\":4,\"amount\":\"0\",\"rec_amount\":\"\",\"payment_desc\":\"\",\"temporary\":\"0\",\"authentication\":\"1\",\"products\":[{\"id\":\"\",\"name\":\"\",\"description\":\"\",\"quantity\":\"1\",\"discount\":\"0.25\",\"amount\":\"995\",\"unit_price\":\"3980\",\"ori_unit_price\":\"3980\",\"product_id\":\"302\",\"sale_type_price\":\"\"}]}"
    logger.info paramsHash
    logger.info JSON.parse "{\"delivery_address\":\"\\u897f\"}"
  end

  #为assembly补充上产品表。
  def fix_assembly
#    assemblys = AssemblyOrder.all
#    assemblys.each do |assembly|
#      assemblyOrderProduct = AssemblyOrderProduct.new
#      assemblyOrderProduct.product_id = assembly.product_id
#      assemblyOrderProduct.quantity = assembly.quantity
#      assembly.assembly_order_products << assemblyOrderProduct
#      assembly.save!
#    end
  end

  def test_lod
    #diffs = Loan.diff_loan_delivery(params[:id])
    #logger.info diffs.length

    diffs = Loan.diff_loan_returned(params[:id])
    logger.info diffs.length

  end

  def subwhere
    assemblyOrder = AssemblyOrder.find(150)
    assemblyOrderDetals = assemblyOrder.assembly_order_details.where("assembly_order_product_id = 158")
    logger.info assemblyOrderDetals.to_json()
  end


end

